package com.zzp.sms.security.service;

import com.zzp.sms.security.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 佐斯特勒
 * <p>
 * 用户详情实现服务
 * </p>
 * @version v1.0.0
 * @date 2020/1/13 13:48
 * @see UserDetailsServiceImpl
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info(s + "用户登录了");
        var user = sysUserService.getSysUserByUsernameOrPhoneNum(s);
        if (user==null){
            log.error("获取的用户信息为空");
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new User(s,user.getPassword(),authorities(user.getProcess()));
    }

    /**
     * 权限设置
     * @param process 用户进程
     * @return 权限认证集合
     */
    private List<GrantedAuthority> authorities(List<String> process) {
        var list = new ArrayList<GrantedAuthority>();
        process.forEach(pro -> list.add(new SimpleGrantedAuthority(pro)));
        return list;
    }

}
